$(function() {
	initCustomerLevelGrid();
	//Tabs点击事件
	$('#myTabs a').click(function (e) {
	  e.preventDefault(); 
	  var href = $(this).attr('href');  
	  if (href == "#customerLevel") {
		  initCustomerLevelGrid();
	  } else if (href == "#customerType") {
		  //initCustomerTypeGrid();
	  } else if (href == "#marketLevel") {
		  initMarketLevelGrid();
	  } else if (href == "#customerField") { 
		  initCustomFieldTable();
	  }
	  $(this).tab('show');
	})
	//新增客户等级按钮点击事件
	$('#btnAdd_customerLevel').on('click', function(){
		$('#layer_opt_status').val(''); 
		var url = rootPath + '/customerLevel/toAddCustomerLevel';
		showDialogUrl('新增', 600, 300, url, function(index){
			layer.close(index);
			initCustomerLevelGrid();
		})
	})
	//新增客户类型按钮点击事件
	/*$('#btnAdd_customerType').on('click', function(){
		$('#layer_opt_status').val(''); 
		var url = rootPath + '/customerType/toAddCustomerType';
		showDialogUrl('新增', 600, 300, url, function(index){
			layer.close(index);
			initCustomerTypeGrid();
		})
	})*/
	//新增市场等级按钮点击事件
	$('#btnAdd_marketLevel').on('click', function(){
		$('#layer_opt_status').val(''); 
		var url = rootPath + '/marketLevel/toAddMarketLevel';
		showDialogUrl('新增', 600, 300, url, function(index){
			layer.close(index);
			initMarketLevelGrid();
		})
	})
	// 查询
	$('#btnQuery_customField').on('click', function() {
		sys.reloadTable('customerCustomFieldTable');
	});
	// 清空
	$('#btnClear_customField').on('click', function() {
		$("#fieldName").val(""); 
	});
	//新增客户自定义属性按钮点击事件
	$('#btnAdd_customField').on('click', function(){
		$('#layer_opt_status').val(''); 
		var url = rootPath + '/customerCustomField/toAddCustomerCustomField';
		var index = showDialogUrl('新增', 800, 400, url, function(index){
			var optStatus = $('#layer_opt_status').val();
			if (optStatus == '1') {
				initCustomFieldTable();
			}
			layer.close(index);
		})
		layer.full(index);
	})
})

/**
 * 排序
 * @param optType 操作类型 1 客户等级配置  2 客户类型配置 3 客户标签配置 4 市场等级配置
 * @param direction 排序移动方向 1 上移 0 置顶 -1 下移
 * @param id 主键ID
 */
function sort(optType, direction, id) {  
	var url = rootPath + '/sort';
	var tableName = "";
	if (optType == '1') {
		tableName = "eb_customer_level";
	} else if (optType == '2') {
		tableName = "eb_customer_type";
	} else if (optType == '4') {
		tableName = "eb_market_level";
	}
	$.ajax({
		type: 'POST',
		url: url,
		data: {direction: direction, tableName: tableName, id: id},
		success: function(data){
			if (data.code == '1') {
				if (optType == '1') {
					initCustomerLevelGrid();
				} else if (optType == '2') {
					//initCustomerTypeGrid();
				} else if (optType == '4') {
					initMarketLevelGrid();
				}
			}
		}
	})
}

/**
 * 编辑行 
 * @param optType 操作类型 1 客户等级配置  2 客户类型配置 3 客户标签配置 4 市场等级配置
 * @param id 主键ID
 */
function editRow(optType, id) {
	var url = "";
	if (optType == '1') {
		url = rootPath + '/customerLevel/toUpdateCustomerLevel?id='+id;
	} else if (optType == '2') {
		//url = rootPath + '/customerType/toUpdateCustomerType?id='+id;
	} else if (optType == '4') {
		url = rootPath + '/marketLevel/toUpdateMarketLevel?id='+id;
	}
	$("#layer_opt_status").val(""); //初始化弹出框操作状态
	showDialogUrl('编辑', 600, 300, url,
		function(){
			var layer_opt_status = $("#layer_opt_status").val(); //获取弹出框操作状态(确定1 取消 0)
			if (layer_opt_status == "1") { //如果是确定
				if (optType == '1') {
					initCustomerLevelGrid();
				} else if (optType == '2') {
					//initCustomerTypeGrid();
				} else if (optType == '4') {
					initMarketLevelGrid();
				}
			}
		}
	);
}

/**
 * 删除行 
 * @param optType 操作类型 1 客户等级配置  2 客户类型配置 3 客户标签配置 4 市场等级配置
 * @param id 主键ID
 */
function removeRow(optType, id) {
	var url = "";
	if (optType == '1') {
		url = rootPath + '/customerLevel/deleteCustomerLevel?id='+id;
	} else if (optType == '2') {
		//url = rootPath + '/customerType/deleteCustomerType?id='+id;
	} else if (optType == '4') {
		url = rootPath + '/marketLevel/deleteMarketLevel?id='+id;
	}
	showConfirm("确定要删除？", function(){
		$.ajax({
			type: 'POST',
			url: url,
			async: false,
			data: {id: id},
			dataType: 'json',
			success: function(data) {
				if (data.code == '1') {
					if (optType == '1') {
						initCustomerLevelGrid();
					} else if (optType == '2') {
						//initCustomerTypeGrid();
					} else if (optType == '4') {
						initMarketLevelGrid();
					}
				} else {
					showErr(data.msg);
				}
			}
		});
	})
};

function formatOptCell(value, row, index, optType) {
	var options = $('#customerLevelTable').bootstrapTable("getOptions");
	var pageNumber = options.pageNumber;
	var lastRowIndex = $('#customerLevelTable').bootstrapTable('getData').length;
	var strHtml = "";
	if (index != 0 || pageNumber != 1) {
		strHtml += "<a class='btn btn-primary btn-xs' onclick='sort("+optType+", 1, "+row.id+")'><i class='fa fa-arrow-up'></i>上移</a>";
	}
	if (lastRowIndex - 1 != index) {
		strHtml += "<a class='btn btn-primary btn-xs' onclick='sort("+optType+", -1, "+row.id+")'><i class='fa fa-arrow-down'></i>下移</a>";
	}
	if (index != 0 || pageNumber != 1) {
		strHtml += "<a class='btn btn-primary btn-xs' onclick='sort("+optType+", 0, "+row.id+")'>置顶</a>";
	}
	strHtml += "<a class='btn btn-warning btn-xs' onclick='editRow("+optType+", "+row.id+")'>编辑</a>";
	strHtml += "<a class='btn btn-danger btn-xs' onclick='removeRow("+optType+", "+row.id+")'>删除</a>";
	return strHtml;
}

/**
 * 加载客户等级配置数据 
 */
function initCustomerLevelGrid(){
	// 定义列
	var columns = [
		{
				field : 'no',
				title : '序号',
				align : 'left',
				formatter : function(value, row, index) {
					return index + 1;
				}
		},
		{
				field : 'levelName',
				title : '级别名称',
				align : 'center'
		},
		{	
			field : '#',
			title : '操作',
			align : 'center',
			formatter : function(value, row, index) {
    			return formatOptCell(value, row, index, 1);
			}
		}, ];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) { 
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码 
		};
	};
	
	var url = rootPath + "/customerLevel/listCustomerLevelPage"; // 请求json数据的服务器地址
	sys.initTable('customerLevelTable', {
		url : url,
		queryParams : queryParams,
		pageSize: 50,
		columns : columns,
		striped : true,
		clickToSelect : true,
		//cookie: true,
		//cookiesEnabled: ['bs.table.pageNumber', 'bs.table.pageList', 'bs.table.columns']
	});
}

/**
 * 加载客户类型配置数据 
 */
function initCustomerTypeGrid(){
	// 定义列
	var columns = [
		{
				field : 'no',
				title : '序号',
				align : 'left',
				formatter : function(value, row, index) {
					return index + 1;
				}
		},
		{
				field : 'typeName',
				title : '客户类型名称',
				align : 'center'
		},
		{	
			field : '#',
			title : '操作',
			align : 'center',
			formatter : function(value, row, index) {
				return formatOptCell(value, row, index, 2);
			}
		}, ];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) { 
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码 
		};
	};
	
	var url = rootPath + "/customerType/listCustomerTypePage"; // 请求json数据的服务器地址
	sys.initTable('customerTypeTable', {
		url : url,
		queryParams : queryParams,
		pageSize: 50,
		columns : columns,
		striped : true,
		clickToSelect : true
	});
}

/**
 * 加载市场等级配置数据 
 */
function initMarketLevelGrid(){
	// 定义列
	var columns = [
		{
				field : 'no',
				title : '序号',
				align : 'left',
				formatter : function(value, row, index) {
					return index + 1;
				}
		},
		{
				field : 'level',
				title : '市场等级',
				align : 'center'
		},
		{	
			field : '#',
			title : '操作',
			align : 'center',
			formatter : function(value, row, index) {
				return formatOptCell(value, row, index, 4);
			}
		}, ];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) {
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
		};
	};
	
	var url = rootPath + "/marketLevel/listMarketLevelPage"; // 请求json数据的服务器地址
	sys.initTable('marketLevelTable', {
		url : url,
		queryParams : queryParams,
		pageSize: 50,
		columns : columns,
		striped : true,
		clickToSelect : true
	});
}

/**
 * 初始化自定义属性表格 
 */
function initCustomFieldTable(){ 
	// 定义列
	var columns = [
		{
			field : 'no',
			title : '序号',
			align : 'left',
			valign: 'middle',
			formatter : function(value, row, index) {
				return index + 1;
			}
		},
		{
			field : 'fieldName',
			title : '字段名称 ',
			align : 'center',
			valign: 'middle',
		},
		{
			field : 'fieldType',
			title : '字段类型 ',
			align : 'center',
			valign: 'middle',
			formatter : function(value, row, index) {
				if (value == "1") {
					return "文本";
				} else if (value == "2") {
					return "单选";
				} else if (value == "3") {
					return "多选";
				}
			}
		},
		{ 	
			field: 'status',
			title: '状态',  
			align: "center",  
			valign: 'middle',
			formatter: function (value, row, index) {
    		   if (value == '0') {
    			   return "<span class='label label-danger'>停用</span>";
    		   } else {
    			   return "<span class='label label-success'>启用</span>";
    		   }
           }   
        },
		{	
			field : '#',
			title : '操作',
			align : 'center',
			valign: 'middle',
			formatter : function(value, row, index) {
				var strHtml = "";
				if (row.status == "0") {
					strHtml += "<a class='btn btn-success btn-xs' onclick='optCustomFieldStatus("+row.id+", "+row.status+")'>启用</a>";
				} else if (row.status == "1") {
					strHtml += "<a class='btn btn-danger btn-xs' onclick='optCustomFieldStatus("+row.id+", "+row.status+")'>停用</a>";
				}
				strHtml += "<a class='btn btn-warning btn-xs' onclick='editCustomField("+row.id+")'>编辑</a>";
				strHtml += "<a class='btn btn-danger btn-xs' onclick='removeCustomFiled("+row.id+")'>删除</a>";
				return strHtml;
			}
		}, ];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) {
	
		var fieldName =  $("#fieldName").val();
		
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
			fieldName : fieldName,  
		};
	};
	
	var url = rootPath + "/customerCustomField/listCustomerCustomFieldPage"; // 请求json数据的服务器地址
	sys.initTable('customerCustomFieldTable', {
		url : url,
		queryParams : queryParams,
		columns : columns,
		striped : true,
		clickToSelect : true
	});
}

function editCustomField(id) {
	$('#layer_opt_status').val(''); 
	var url = rootPath + '/customerCustomField/toUpdateCustomerCustomField?id='+id;
	showDialogUrl('编辑', 800, 500, url, function(index){
		var optStatus = $('#layer_opt_status').val();
		if (optStatus == '1') {
			initCustomFieldTable();
		}
		layer.close(index);
	})
}

function removeCustomFiled(id) {
	showConfirm("确定要删除？", function(){
		$.ajax({
			type: 'POST',
			url: rootPath + "/customerCustomField/deleteCustomerCustomField",
			async: false,
			data: {id: id},
			dataType: 'json',
			success: function(data) {
				if (data.code == '1') {
					initCustomFieldTable();
				}
			}
		});
	})
}

function optCustomFieldStatus(id, status) {
	var info = "";
	if (status == "0") {
		info = "确定要启用?";
	} else {
		info = "确定要停用";
	}
	showConfirm(info, function(){
		$.ajax({
			type: 'POST',
			url: rootPath + "/customerCustomField/saveOrUpdateCustomerCustomField",
			async: false,
			data: {id: id, status: status == '0' ? '1' : '0'},
			dataType: 'json',
			success: function(data) {
				if (data.code == '1') {
					initCustomFieldTable();
				}
			}
		});
	})
}